<?php
defined('_VALID_MOS') or die('Direct Access to this location is not allowed.');
/**
*
* Version : 3.1
* ID      : ptype shipping module
* Author  : Adam Hughes
* Site    : www.questtech.co.uk
* License : Free
*
*/

/**
* 
*
* This class will allow you to set up a minimum rate for free shipping
* a rate for anything under the minimum rate
* Also a 'bypass type(s)' which allows for any a set rate if any 
* items in a particular type are in the order
* @copyright (C) 2006 Adam Hughes
* 
*******************************************************************************
*/

		
class ptype {

	var $classname = "ptype";

	function list_rates( &$d ) {
		global $total, $tax_total, $CURRENCY_DISPLAY, $vmLogger;
		$db =& new ps_DB;
		$dbv =& new ps_DB;

		$cart = $_SESSION['cart'];

		/** Read current Configuration ***/
		require_once(CLASSPATH ."shipping/".$this->classname.".cfg.php");
	
		if ( $_SESSION['auth']['show_price_including_tax'] != 1 ) {
			$taxrate = 1;
			$order_total = $total + $tax_total;
		}
		else {
			$taxrate = $this->get_tax_rate() + 1;
			$order_total = $total;
		}
		
		//Set variables used in rate decision
		$rate1_ship = ptype_RATE1_AMOUNT;
		$rate2_ship = ptype_RATE2_AMOUNT;
		$rate3_ship = ptype_RATE3_AMOUNT;
		$rate4_ship = ptype_RATE4_AMOUNT;
		$rate5_ship = ptype_RATE5_AMOUNT;

		$rate1_charge = ptype_RATE1_CHG;
		$rate2_charge = ptype_RATE2_CHG;
		$rate3_charge = ptype_RATE3_CHG;
		$rate4_charge = ptype_RATE4_CHG;
		$rate5_charge = ptype_RATE5_CHG;
		$maxrate_charge = ptype_MAXRATE_CHG;
		
		$bypass1_amount = ptype_BYPASS1_AMOUNT;
		$bypass2_amount = ptype_BYPASS2_AMOUNT;
		$bypass3_amount = ptype_BYPASS3_AMOUNT;
		
		$bypass1_group = ptype_BYPASS1_GROUP;
		$bypass2_group = ptype_BYPASS2_GROUP;
		$bypass3_group = ptype_BYPASS3_GROUP;
		
		$bypass1_label = ptype_BYPASS1_LABEL;		
		$bypass2_label = ptype_BYPASS2_LABEL;
		$bypass3_label = ptype_BYPASS3_LABEL;
		
		//Now create a comma delimited list of products from the order (which is used to query the db)	
		$q = "";
		for ($i=0; $i < $cart[idx]; $i++)
			{
				if ($i != 0) $q .= ",";
				$q .= $cart[$i]["product_id"];
			}
		//Now Create the sql to query the database to check for products in the bypass groups
		$sqltorun = "SELECT product_type_id from";
		$sqltorun .= " (SELECT product_type_id from #__{vm}_product_product_type_xref as a WHERE product_id in (";
		$sqltorun .= $q;
		$sqltorun .= ")) b WHERE product_type_id in (";
		$sqltorun .= $bypass1_group;
		$sqltorun .= ",";
		$sqltorun .= $bypass2_group;
		$sqltorun .= ",";
		$sqltorun .= $bypass3_group;
		$sqltorun .= ")";
		$vmLogger->debug( "PTYPE Shipping Module: Generated Sql for product check is : {$sqltorun}" );

	//Now we check (using the vm db layer if any of the products are in the bypass group
	require_once( CLASSPATH. 'ps_database.php' );
	$db->setQuery("{$sqltorun}");	
	$typeidlist = array();
	$typeidlist = $db->loadResultArray(0);
	//If the query has any record then work though all three bypass groups 
	if (count($typeidlist) > 0) 
		{
			$vmLogger->debug( "PTYPE Shipping Module: I have found products in the bypass group(s)");
			//echo "<b>DEBUG</b>: typeidlist array is:<br />";
			//print_r($typeidlist);
			//echo "<br />";
			//echo "<b>DEBUG</b>: Rate1 : {$bypass1_group} , {$bypass1_amount}<br />";
			//echo "<b>DEBUG</b>: Rate2 : {$bypass2_group} , {$bypass2_amount}<br />";
			//echo "<b>DEBUG</b>: Rate3 : {$bypass3_group} , {$bypass3_amount}<br />";
			if (in_array($bypass1_group,$typeidlist))
				{
					//In bypass group 1
					$vmLogger->debug( "PTYPE Shipping Module: I have found products in the bypass group 1");
					$charge = $bypass1_amount;
					$ship_label = $bypass1_label;
				}
			elseif (in_array($bypass2_group,$typeidlist))
				{
					//In bypass group 2
					$vmLogger->debug( "PTYPE Shipping Module: I have found products in the bypass group 2");
					$charge = $bypass2_amount;
					$ship_label = $bypass2_label;
				}
			elseif (in_array($bypass3_group,$typeidlist))
				{
					//In bypass group 3
					$vmLogger->debug( "PTYPE Shipping Module: I have found products in the bypass group 4");
					$charge = $bypass3_amount;
					$ship_label = $bypass3_label;
				}
			$charge *= $taxrate;
			$ship = $rate1_ship;			
		}
	else
		{
		//Now if it wasn't in the bypass group
		// We now have to check with rate the invoice total is in
			if($order_total <= $rate1_ship)
				{
					$vmLogger->debug( "PTYPE Shipping Module: Invoice total less than rate1 : rate1 shipping being used");
					$charge = $rate1_charge;
					$charge *= $taxrate;
					$ship = $rate1_ship;
					$ship_label = "Standard Shipping for invoice total under to {$rate1_amount}";
				}
			if($order_total > $rate1_ship AND $order_total <= $rate2_ship)
				{
					$vmLogger->debug( "PTYPE Shipping Module: Invoice between rate1 & 2 : rate2 shipping being used");
					$charge = $rate2_charge;
					$charge *= $taxrate;
					$ship = $rate2_ship;
					$ship_label = "Standard Shipping for invoice total between {$rate1_amount} and {$rate2_amount}";
				}
			if($order_total > $rate2_ship AND $order_total <= $rate3_ship)
				{
					$vmLogger->debug( "PTYPE Shipping Module: Invoice between rate2 & 3 : rate3 shipping being used");
					$charge = $rate3_charge;
					$charge *= $taxrate;
					$ship = $rate3_ship;
					$ship_label = "Standard Shipping for invoice total between {$rate2_amount} and {$rate3_amount}";
				}		
			if($order_total > $rate3_ship AND $order_total <= $rate4_ship)
				{
					$vmLogger->debug( "PTYPE Shipping Module: Invoice between rate3 & 4 : rate4 shipping being used");
					$charge = $rate4_charge;
					$charge *= $taxrate;
					$ship = $rate4_ship;
					$ship_label = "Standard Shipping for invoice total between {$rate3_amount} and {$rate4_amount}";
				}
			if($order_total > $rate4_ship AND $order_total <= $rate5_ship)
				{
					$vmLogger->debug( "PTYPE Shipping Module: Invoice between rate4 & 5 : rate5 shipping being used");
					$charge = $rate5_charge;
					$charge *= $taxrate;
					$ship = $rate5_ship;
					$ship_label = "Standard Shipping for invoice total between {$rate4_amount} and {$rate5_amount}";
				}
			if($order_total > $rate5_ship)
				{
					$vmLogger->debug( "PTYPE Shipping Module: Invoice greater than rate5 : maxrate shipping being used");
					$charge = $maxrate_charge;
					$charge *= $taxrate;
					$ship = $rate5_ship;
					$ship_label = "Standard Shipping for invoice total greater than {$rate5_amount}";
				}
			}
		//Now set the shipping rate up
		$shipping_rate_id = urlencode($this->classname."|STD|Standard Shipping under ".$ship."|".$charge);
		$html = "";
		$html .= "\n<input type=\"radio\" name=\"shipping_rate_id\" checked=\"checked\" id=\"ptype_shipping_rate\" value=\"$shipping_rate_id\" />\n";
		$html .= "<label for=\"ptype_shipping_rate\">{$ship_label}: ";
		$html .= $CURRENCY_DISPLAY->getFullValue($charge);
		$html .= "</label>";
		$_SESSION[$shipping_rate_id] = 1;

		echo $html;
		return true;

	}

	function get_rate( &$d ) {

		$shipping_rate_id = $d["shipping_rate_id"];
		$is_arr = explode("|", urldecode(urldecode($shipping_rate_id)) );
		$order_shipping = $is_arr[3];
		return $order_shipping;

	}
	
		
	function get_tax_rate() {

		/** Read current Configuration ***/
		require_once(CLASSPATH ."shipping/".$this->classname.".cfg.php");

		if( intval(ptype_TAX_CLASS)== 0 )
		return( 0 );
		else {
			require_once( CLASSPATH. "ps_tax.php" );
			$tax_rate = ps_tax::get_taxrate_by_id( intval(ptype_TAX_CLASS) );
			return $tax_rate;
		}
	}
	
	/* Validate this Shipping method by checking if the SESSION contains the key
	* @returns boolean False when the Shipping method is not in the SESSION
	*/
	function validate( $d ) {

		$shipping_rate_id = $d["shipping_rate_id"];

		if( array_key_exists( $shipping_rate_id, $_SESSION )) {
			
			return true;
		}
		else {
			return false;
		}
	}
	/**
    * Show all configuration parameters for this Shipping method
    * @returns boolean False when the Shipping method has no configration
    */
	function show_configuration() {
		global $VM_LANG;
		/** Read current Configuration ***/
		require_once(CLASSPATH ."shipping/".$this->classname.".cfg.php");
    ?>
    <h4>Standard Invoice Amount Values</h4>
    <table>
    <tr>
        <td><strong>Invoice Amount for Rate1 shipping charge :</strong></td>
		<td>
            <input type="text" name="ptype_RATE1_AMOUNT" class="inputbox" value="<?php echo ptype_RATE1_AMOUNT ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("Is the invoice total is the same or less than this than shipping rate 1 is applied") ?> 
        </td>
    </tr>
	<tr>
        <td><strong>Invoice Amount for Rate2 shipping charge :</strong></td>
		<td>
            <input type="text" name="ptype_RATE2_AMOUNT" class="inputbox" value="<?php echo ptype_RATE2_AMOUNT ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("If the invoice value is between rate1 and this (rate2) then Shipping Charge Rate2 is applied") ?> 
        </td>	
	</tr>
	<tr>
        <td><strong>Invoice Amount for Rate3 shipping charge :</strong></td>
		<td>
            <input type="text" name="ptype_RATE3_AMOUNT" class="inputbox" value="<?php echo ptype_RATE3_AMOUNT ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("If the invoice value is between rate2 and this (rate3) then Shipping Charge Rate3 is applied") ?> 
        </td>	
	</tr>
	<tr>
        <td><strong>Invoice Amount for Rate4 shipping charge :</strong></td>
		<td>
            <input type="text" name="ptype_RATE4_AMOUNT" class="inputbox" value="<?php echo ptype_RATE4_AMOUNT ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("If the invoice value is between rate3 and this (rate4) then Shipping Charge Rate4 is applied") ?> 
        </td>	
	</tr>
	<tr>
        <td><strong>Invoice Amount for Rate5 shipping charge :</strong></td>
		<td>
            <input type="text" name="ptype_RATE5_AMOUNT" class="inputbox" value="<?php echo ptype_RATE5_AMOUNT ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("If the invoice value is between rate4 and this (rate5) then Shipping Charge Rate5 is applied") ?> 
        </td>	
	</tr>
    <tr>
        <td><strong>Rate1 Shipping Charge:</strong></td>
		<td>
            <input type="text" name="ptype_RATE1_CHG" class="inputbox" value="<?php echo ptype_RATE1_CHG ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("This is the rate charged when the invoice amount is below rate1") ?>
        </td>
    </tr>
    <tr>
        <td><strong>Rate2 Shipping Charge:</strong></td>
		<td>
            <input type="text" name="ptype_RATE2_CHG" class="inputbox" value="<?php echo ptype_RATE2_CHG ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("This is the rate charged when the invoice amount is between rate1 and rate2") ?>
        </td>
    </tr>
    <tr>
        <td><strong>Rate3 Shipping Charge:</strong></td>
		<td>
            <input type="text" name="ptype_RATE3_CHG" class="inputbox" value="<?php echo ptype_RATE3_CHG ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("This is the rate charged when the invoice amount is between rate2 and rate3") ?>
        </td>
    </tr>
    <tr>
        <td><strong>Rate4 Shipping Charge:</strong></td>
		<td>
            <input type="text" name="ptype_RATE4_CHG" class="inputbox" value="<?php echo ptype_RATE4_CHG ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("This is the rate charged when the invoice amount is between rate3 and rate4") ?>
        </td>
    </tr>
    <tr>
        <td><strong>Rate5 Shipping Charge:</strong></td>
		<td>
            <input type="text" name="ptype_RATE5_CHG" class="inputbox" value="<?php echo ptype_RATE5_CHG ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("This is the rate charged when the invoice amount is between rate4 and rate4") ?>
        </td>
    </tr>
    <tr>
        <td><strong>MaxRate Shipping Charge:</strong></td>
		<td>
            <input type="text" name="ptype_MAXRATE_CHG" class="inputbox" value="<?php echo ptype_MAXRATE_CHG ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("This is the rate charged when the invoice amount is over rate5") ?>
        </td>
    </tr>
    </table>
    <h4>Bypass (override) product type charges</h4>
    <table>
	<tr>
		<td>
			<b>Bypass Product Shipping Charge 1</b>
		</td>
		<td>
            <input type="text" name="ptype_BYPASS1_AMOUNT" class="inputbox" value="<?php echo ptype_BYPASS1_AMOUNT ?>" />
		</td>
		<td>
        <?php echo mm_ToolTip("This is the flat fee to be charged if the cart has an item from the bypass group 1.") ?>
        </td>
	</tr>
	<tr>
		<td>
			<strong>Bypass Product Group 1</strong>
		</td>
		<td>
			<input type="text" name="ptype_BYPASS1_GROUP" class="inputbox" value="<?php echo ptype_BYPASS1_GROUP ?>" />
		</td>
		<td>
			<?php echo mm_ToolTip("Enter the group you wish to override the shipping.") ?>
		</td>
	</tr>
	  	<tr>
  		<td>
			<b>Bypass Product Label 1</b>
		</td>
		<td>
			<input type="text" name="ptype_BYPASS1_LABEL" class="inputbox" value="<?php echo ptype_BYPASS1_LABEL ?>" />
		</td>
		<td>
			<?php echo mm_ToolTip("Enter the description you wish to see on the shipping page for this rate") ?>
		</td>
	</tr>
	<tr>
		<td>
			<b>Bypass Product Shipping Charge 2</b>
		</td>
		<td>
           	<input type="text" name="ptype_BYPASS2_AMOUNT" class="inputbox" value="<?php echo ptype_BYPASS2_AMOUNT ?>" />
		</td>
		<td>
       		<?php echo mm_ToolTip("This is the flat fee to be charged if the cart has an item from the bypass group 2.") ?>
       	</td>
	</tr>
  	<tr>
  		<td>
			<b>Bypass Product Group 2</b>
		</td>
		<td>
			<input type="text" name="ptype_BYPASS2_GROUP" class="inputbox" value="<?php echo ptype_BYPASS2_GROUP ?>" />
		</td>
		<td>
			<?php echo mm_ToolTip("Enter the group you wish to override the shipping.") ?>
		</td>
	</tr>
	  	<tr>
  		<td>
			<b>Bypass Product Label 2</b>
		</td>
		<td>
			<input type="text" name="ptype_BYPASS2_LABEL" class="inputbox" value="<?php echo ptype_BYPASS2_LABEL ?>" />
		</td>
		<td>
			<?php echo mm_ToolTip("Enter the description you wish to see on the shipping page for this rate") ?>
		</td>
	</tr>
	<tr>
		<td>
			<b>Bypass Product Shipping Charge 3</b>
		</td>
		<td>
           	<input type="text" name="ptype_BYPASS3_AMOUNT" class="inputbox" value="<?php echo ptype_BYPASS3_AMOUNT ?>" />
		</td>
		<td>
       		<?php echo mm_ToolTip("This is the flat fee to be charged if the cart has an item from the bypass group 3.") ?>
       	</td>
	</tr>
  	<tr>
  		<td>
			<b>Bypass Product Group 3</b>
		</td>
		<td>
			<input type="text" name="ptype_BYPASS3_GROUP" class="inputbox" value="<?php echo ptype_BYPASS3_GROUP ?>" />
		</td>
		<td>
			<?php echo mm_ToolTip("Enter the group you wish to override the shipping.") ?>
		</td>
	</tr>
  	<tr>
  		<td>
			<b>Bypass Product Label 3</b>
		</td>
		<td>
			<input type="text" name="ptype_BYPASS3_LABEL" class="inputbox" value="<?php echo ptype_BYPASS3_LABEL ?>" />
		</td>
		<td>
			<?php echo mm_ToolTip("Enter the description you wish to see on the shipping page for this rate") ?>
		</td>
	</tr>
	</table>
	<h4>Tax Information</h4>
	<table>
	<tr>
			<td>
				<strong><?php echo $VM_LANG->_PHPSHOP_UPS_TAX_CLASS ?></strong></td>
			<td>
		  		<?php require_once(CLASSPATH.'ps_tax.php');
				ps_tax::list_tax_value("PTYPE_TAX_CLASS", PTYPE_TAX_CLASS) ?>
			</td>
			<td>
				<?php echo mm_ToolTip($VM_LANG->_PHPSHOP_UPS_TAX_CLASS_TOOLTIP) ?>
			<td>
	  </tr>	

	</table>
   <?php
   // return false if there's no configuration
   return true;
	}
	/**
  * Returns the "is_writeable" status of the configuration file
  * @param void
  * @returns boolean True when the configuration file is writeable, false when not
  */
	function configfile_writeable() {
		return is_writeable( CLASSPATH."shipping/".$this->classname.".cfg.php" );
	}

	/**
	* Writes the configuration file for this shipping method
	* @param array An array of objects
	* @returns boolean True when writing was successful
	*/
	function write_configuration( &$d ) {
	    global $vmLogger;

		$my_config_array = array("ptype_RATE1_AMOUNT" => $d['ptype_RATE1_AMOUNT'],
		"ptype_RATE2_AMOUNT" => $d['ptype_RATE2_AMOUNT'],
		"ptype_RATE3_AMOUNT" => $d['ptype_RATE3_AMOUNT'],
		"ptype_RATE4_AMOUNT" => $d['ptype_RATE4_AMOUNT'],
		"ptype_RATE5_AMOUNT" => $d['ptype_RATE5_AMOUNT'],
		"ptype_RATE1_CHG" => $d['ptype_RATE1_CHG'],
		"ptype_RATE2_CHG" => $d['ptype_RATE2_CHG'],
		"ptype_RATE3_CHG" => $d['ptype_RATE3_CHG'],
		"ptype_RATE4_CHG" => $d['ptype_RATE4_CHG'],
		"ptype_RATE5_CHG" => $d['ptype_RATE5_CHG'],
		"ptype_MAXRATE_CHG" => $d['ptype_MAXRATE_CHG'],
		"ptype_BYPASS1_AMOUNT" => $d['ptype_BYPASS1_AMOUNT'],
		"ptype_BYPASS1_GROUP" => $d['ptype_BYPASS1_GROUP'],
		"ptype_BYPASS1_LABEL" => $d['ptype_BYPASS1_LABEL'],
		"ptype_BYPASS2_AMOUNT" => $d['ptype_BYPASS2_AMOUNT'],
		"ptype_BYPASS2_GROUP" => $d['ptype_BYPASS2_GROUP'],
		"ptype_BYPASS2_LABEL" => $d['ptype_BYPASS2_LABEL'],
		"ptype_BYPASS3_AMOUNT" => $d['ptype_BYPASS3_AMOUNT'],
		"ptype_BYPASS3_GROUP" => $d['ptype_BYPASS3_GROUP'],
		"ptype_BYPASS3_LABEL" => $d['ptype_BYPASS3_LABEL'],
		"ptype_TAX_CLASS" => $d['ptype_TAX_CLASS']
		);
		$config = "<?php\n";
		$config .= "defined('_VALID_MOS') or die('Direct Access to this location is not allowed.'); \n\n";
		foreach( $my_config_array as $key => $value ) {
			$config .= "define ('$key', '$value');\n";
		}

		$config .= "?>";

		if ($fp = fopen(CLASSPATH ."shipping/".$this->classname.".cfg.php", "w")) {
			fputs($fp, $config, strlen($config));
			fclose ($fp);
			return true;
		}
		else {
			$vmLogger->err( "Error writing to configuration file" );
			return false;
		}
	}
}


?>
